package com.onpositive.wiki3.db.impl;

import java.util.ArrayList;

import com.carrotsearch.hppc.IntOpenHashSet;
import com.onpositive.nlp.inflector.English;
import com.onpositive.wiki3.db.IWikiDB;

public class PrimaryArticleFinder {

	interface IWordCorrector {

		String newWordForm(String word);
	}

	static ArrayList<IWordCorrector> cs = new ArrayList<PrimaryArticleFinder.IWordCorrector>();

	static {
		cs.add(new IWordCorrector() {

			@Override
			public String newWordForm(String word) {
				return Character.toUpperCase(word.charAt(0))
						+ word.substring(1).toLowerCase();
			}
		});
	}

	public static int findPrimaryForm(String word, IWikiDB db) {
		int id = db.getTitleMapper().getId(word);
		if (id != -1) {
			return id;
		}
		for (IWordCorrector wa : cs) {
			String newWordForm = wa.newWordForm(word);
			int id2 = db.getTitleMapper().getId(newWordForm);
			if (id2 != -1) {
				return id2;
			}
		}
		int redirect = db.getRedirectAccess().getRedirect(id);
		if (redirect != -1) {
			return redirect;
		}
		return id;
	}

	public static int findPrimaryCategory(String primaryForm, IWikiDB db) {
		IntOpenHashSet allCats = ((CategoryAccessImpl) db.getCategoryAccessor())
				.getAllCats();
		int id = findPrimaryForm(primaryForm, db);
		if (allCats.contains(id)) {
			return id;
		}
		String plural = English.plural(primaryForm);
		id = findPrimaryForm(plural, db);
		if (allCats.contains(id)) {
			return id;
		}
		return -1;
	}
}
